package org.budo.mongo.jdbc.driver;

import java.sql.SQLException;
import java.sql.Types;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.budo.jdbc.driver.BudoJdbcResultSetMetaData;

/**
 * @author li
 */
public class BudoMongoJdbcResultSetMetaData extends BudoJdbcResultSetMetaData {
    private volatile Map<String, Integer> columnLabelToIndexCacheMap = new ConcurrentHashMap<String, Integer>();

    public BudoMongoJdbcResultSetMetaData() {}

    public BudoMongoJdbcResultSetMetaData(String[] columnNames) {
        this.columnNames(columnNames);
    }

    @Override
    public String getSchemaName(int column) throws SQLException {
        return "";
    }

    @Override
    public int getColumnDisplaySize(int column) throws SQLException {
        return Integer.MAX_VALUE;
    }

    /**
     * @return return 0 if not found
     */
    public int getColumnIndexByLabel(String columnLabel) {
        Integer columnIndex = columnLabelToIndexCacheMap.get(columnLabel);
        if (null != columnIndex) {
            return columnIndex;
        }

        columnIndex = this.doGetColumnIndexByLabel(columnLabel);
        if (columnIndex > 0) {
            columnLabelToIndexCacheMap.put(columnLabel, columnIndex);
        }
        return columnIndex;
    }

    private int doGetColumnIndexByLabel(String columnLabel) {
        for (int i = 0; i < this.columnLabels().length; i++) {
            if (columnLabel.equals(this.columnLabels()[i])) {
                return i + 1;
            }
        }
        return 0;
    }

    public String getColumnLabel(int column) throws SQLException {
        if (null == this.columnLabels()) {
            return this.getColumnName(column);
        }

        return this.columnLabels()[column - 1];
    }

    public int getColumnType(int column) throws SQLException {
        if (null == this.columnTypes()) {
            return Types.CHAR;
        }

        return this.columnTypes()[column - 1];
    }

    public String getColumnClassName(int column) throws SQLException {
        if (null == this.columnClassNames()) {
            return Object.class.getName();
        }

        return this.columnClassNames()[column - 1];
    }
}